<script setup lang="ts">
import type {FormTree} from "@/interfaces/components/Form";
import type {Project} from "@/interfaces/views/project/project";
import CdlForm from "@/components/form";
import {ref} from "vue";
import {
  useCreateProjectApi,
  useProjectInfoApi,
  useUpdateProjectApi
} from "@/api/project/project";
import {useRoute, useRouter} from "vue-router";
import type {FormData} from "@/interfaces/components/Page";
import type {Information} from "@/interfaces/views/project/information";
import {mergeObjects} from "@/utils/utilities";
import {appStore} from "@/store/modules/app";
import {ElMessage} from "element-plus/es";
import {useShipperListApi} from "@/api/vehicle/shipper";
import {useUserListApi} from "@/api/sys/user";

const router = useRouter()
const route = useRoute()
const store = appStore()
if(route.query.id) init()

// 基本
const basicFormEl = ref()
const basicFormTree: FormTree<Project> = [
  [
    {label: "订单名称", component: "input", prop: "name", rule: [{
        required: true, message: '项目名称不能为空', trigger: 'blur'
      }]},
    {label: "订单类型", component: "select", prop: "typeId", options: store.getDict("project_type"),
      optionProps: {label: "dictLabel", value: "dictValue"}, rule: [{
        required: true, message: '项目类型不能为空', trigger: 'change'
      }]},
    {label: "订单负责人", component: "select", prop: "managerId", serviceOptionKey: "userList",
      optionProps: {label: "realName", value: "id"}, rule: [{
        required: true, message: '项目负责人不能为空', trigger: 'blur'
      }]},
  ],
  [
    {label: "托运人", component: "select", prop: "shipperId", serviceOptionKey: "shipper",
      optionProps: {label: "contact", value: "id"}, changeMethod: (val, data)=> {
        const shipper = shipperList.find(item => item.id === val)
        data.legalPerson = shipper.legalPerson
        data.idNum = shipper.idNum
      }, rule: [{
        required: true, message: '托运人不能为空', trigger: 'blur'
      }]},
    {label: "托运人法人名称", component: "input", prop: "legalPerson"
      , rule: [{
        required: true, message: '托运人法人名称不能为空', trigger: 'blur'
      }]},
    {label: "托运人信用代码", component: "input", prop: "idNum"
      , rule: [{
        required: true, message: '托运人信用代码不能为空', trigger: 'blur'
      }]},
  ],
  [
    {label: "货物名称", component: "input", prop: "cargoName"
      , rule: [{
        required: true, message: '货物名称不能为空', trigger: 'blur'
      }]},
    {label: "货物毛重（kg）", component: "input", prop: "cargoGrossWeight"
      , rule: [{
        required: true, message: '货物毛重不能为空', trigger: 'blur'
      }]},
    {label: "货物分类代码", component: "input", prop: "cargoTypeId"},
  ],
  [
    {label: "装货地址", component: "input", prop: "loadingAddress"},
    {label: "卸货地址", component: "input", prop: "unloadingAddress"},
    {label: "订单预估完成日期", component: "datePicker", prop: "expectedTime"},
  ],
  [
    {label: "付款方式", component: "radio", prop: "payMode", options: store.getFormatDict("payment_method"),
      optionProps: {label: "dictLabel", value: "dictValue"}, disabled: !route.query.emit,
      rule: {required: true, message: "必须选择付款方式", trigger: "change"}
    }
  ]
]
const basicFormData = ref<FormData<Project>>({
  id: undefined,
  name: "",
  typeId: "",
  shipperId: undefined,
  shipperName: "",
  legalPerson: "",
  idNum: "",
  managerId: undefined,
  managerName: "",
  cargoName: "",
  cargoGrossWeight: 0,
  cargoTypeId: 0,
  payMode: undefined,
  loadingAddress: "",
  unloadingAddress: "",
  expectedTime: ""
})

// 附加信息
const extraEl = ref()
const extraFormTree: FormTree<Information> = [
  [
    {label: "保险公司", component: "input", prop: "insurance"},
    {label: "保险单号", component: "input", prop: "insuranceSn"},
    {}
  ],
    [
      {label: "备注", component: "input", prop: "remark", type: "textarea",
        style: "width: 50%"}
    ]
]
const extraFormData = ref<FormData<Information>>({
  insurance: "",
  insuranceSn: "",
  remark: ""
})


/**
 * 获取项目类型列表
 */
function getProjectTypeList(){
  return new Promise((resolve, reject) => {
    // todo 暂时不需要
    // useProjectTypeListApi().then(res =>{
    //   resolve(res.data)
    // })
  })
}
let shipperList: any[] = []
/**
 * 获取托运人列表
 */
function getShipperList(){
  return new Promise((resolve, reject) => {
    useShipperListApi().then(res =>{
      shipperList = res.data
      resolve(res.data)
    })
  })
}
let userList: any[] = []
/**
 * 获取用户列表
 */
function getUserList(){
  return new Promise((resolve, reject) => {
    useUserListApi().then(res =>{
      userList = res.data
      resolve(res.data)
    })
  })
}

/**
 * 提交
 */
async function submit(){
  const basic = await basicFormEl.value.parentSubmit()
  const extra = await extraEl.value.parentSubmit()
  const data: {[key: string]: any} = {}
  Object.assign(data, basic, extra)
  data.managerName = userList.find(item => item.id === data.managerId)?.realName
  data.shipperName = shipperList.find(item => item.id === data.shipperId)?.contact
  if(route.query.id){
    useUpdateProjectApi(data).then((res: any)=>{
      if(res.code === 0){
        ElMessage.success("修改成功，自动返回上一页")
        router.back()
      }
    })
  }else {
    useCreateProjectApi(data).then((res: any)=>{
      if(res.code === 0){
        ElMessage.success("创建成功，自动返回上一页")
        router.back()
      }
    })
  }

}
/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}

/**
 * 初始化
 */
function init(){
  useProjectInfoApi(route.query.id as string).then(res =>{
    const {taskList, insurance, insuranceSn, ...rest} = res.data
    mergeObjects(basicFormData.value, rest)
    extraFormData.value.insurance = insurance
    extraFormData.value.insuranceSn = insuranceSn
  })
}
</script>

<template>
  <el-card style="position: relative">
    <button class="back_btn" @click="fallbackPage"></button>
    <h1 class="top_line">基础信息</h1>
    <el-divider></el-divider>
    <CdlForm :model="basicFormData" :template-tree="basicFormTree"
             ref="basicFormEl"
             label-width="130" :init="{shipper: getShipperList, userList: getUserList}"></CdlForm>
    <h1 class="mgt">其他附加信息</h1>
    <el-divider></el-divider>
    <CdlForm :model="extraFormData" ref="extraEl" :template-tree="extraFormTree"></CdlForm>
    <div class="footer_btn">
      <el-button @click="submit">提交</el-button>
      <el-button>取消</el-button>
    </div>
  </el-card>
</template>
